<template>
  <div class="login--wrap2">
    <div class="login--from">
      <div class="login--head">
        <img src="@/assets/img/logo.png" alt="" class="login--head--logo" />
        <span class="login--title">远程自动超声辅助诊断系统</span>
      </div>
      <div class="login--title--wrap">
        <span class="login--title-sub"
          >CORUS-{{ ownModel }}-Remote 阅片评价系统</span
        >
      </div>
      <div class="form--wrap">
        <span class="form--wrap--sub">系统登录</span>
        <a-form
          id="components-form-demo-normal-login"
          :form="form"
          class="login-form"
          :wrapper-col="{ span: 24 }"
        >
          <a-form-item>
            <a-input
              class="login--inp"
              v-decorator="[
                'user',
                { rules: [{ required: true, message: '请输入您的账号!' }] },
              ]"
              placeholder="账号"
              autoComplete="off"
              @blur="handBlur"
            >
              <a-icon slot="prefix" type="user" style="color: #fff" />
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-input-password
              class="login--inp"
              v-decorator="[
                'passwd',
                {
                  rules: [
                    { required: true, message: '请输入您的密码!' },
                    {
                      pattern:
                        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&_])[A-Za-z\d@$!%*?&_]{8,}$/,
                      message:
                        '密码长度至少为8并且包含大小写字母与特殊字符及数字,例如:Zxc_123456!',
                    },
                  ],
                },
              ]"
              type="password"
              placeholder="密码"
              autoComplete="off"
            >
              <a-icon slot="prefix" type="lock" style="color: #fff" />
            </a-input-password>
          </a-form-item>

          <a-form-item v-show="blindShow">
            <div class="login--forgot--wrap">
              <div class="login--blind">是否盲评:</div>
              <div class="login--blind">
                <a-radio-group :options="options" v-model="blind" />
              </div>
            </div>
          </a-form-item>

          <a-form-item>
            <div class="login--forgot--wrap">
              <div class="login--forgot">
                <div class="login--forgot--con" @click="tipsShow = !tipsShow">
                  忘记密码
                </div>
                <span class="login--forgot--tips" v-show="tipsShow">
                  请联系管理员重置密码,联系电话:{{ tel }}
                </span>
              </div>
            </div>
          </a-form-item>

          <a-form-item :wrapper-col="{ span: 24 }">
            <div class="login--btn--wrap">
              <a-popconfirm
                title="确定关机?"
                ok-text="是"
                cancel-text="否"
                @confirm="confirmShotDown"
              >
                <!-- <button type="button" class="login-form-button delete">
                  关机
                </button> -->
              </a-popconfirm>
              <button @click="handleSubmit" class="login-form-button">
                登录
              </button>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script>
import { login, updateUser, getUser,getAdminByLevel } from "@/api/login";
import { encrypt } from "@/utils/cryptoTools";
import { systemShutDown } from "@/api/system";
import { readConfig } from "@/api/readConfig";
import { mapState } from "vuex";
import { isStrongPassword } from "@/utils/cryptoTools";
import { getAllModel } from "@/api/model";
export default {
  name: "Login",
  data() {
    return {
      form: this.$form.createForm(this, { name: "coordinated" }),
      tipsShow: false,
      options: [
        { label: "盲评", value: true },
        { label: "非盲评", value: false },
      ],
      blindShow:true,
      blind: false,
      tel:"17740669751"
    };
  },
  computed: {
    ...mapState(["SERVERBASE_URL", "ownModel"]),
  },
  watch:{
    tipsShow(val){
       if(val){
         getAdminByLevel(this.SERVERBASE_URL,1).then(res=>{
           if(res.code == 200){
             this.tel = res.data.tel;
           }
         })
       }
    }
  },

  async mounted() {
    await this.initConfig(window.SERVERBASE.SERVERBASE_URL);
    console.log("isStrongPassword", isStrongPassword("Cobot_123"));
    console.log("encrypt", encrypt("Cobot_123"));
    const route = this.$route;
    console.log("route?.query.token", route?.query.token);
    if (route?.query.token) {
      const key = `open${Date.now()}`;
      this.$notification.warning({
        message: "提示",
        description: `账号在其他地点登录!`,
        duration: null,
        btn: (h) => {
          return h(
            "a-button",
            {
              props: {
                size: "small",
              },
              on: {
                click: () => {
                  this.$notification.close(key);
                },
              },
            },
            "确定"
          );
        },
        key,
      });
    }
  },
  methods: {
    //初始化配置
    async initConfig(url) {
      const res = await readConfig(url);
      if (res.data) {
        console.log(res.data);
        res.data.SERVERBASE_URL &&
          this.$store.commit("SET_SERVERBASE_URL", res.data.SERVERBASE_URL);
        res.data.RECORD_URL &&
          this.$store.commit("SET_RECORD_URL", res.data.RECORD_URL);
        res.data.imgServerUrl &&
          this.$store.commit("SET_IMGSERVER", res.data.imgServerUrl);
        res.data.aboutInfo &&
          this.$store.commit("SET_ABOUTINFO", res.data.aboutInfo);
        res.data.MANAGA_URL &&
          this.$store.commit("SET_MANAGA", res.data.MANAGA_URL);
        res.data.idleTime &&
          this.$store.commit("SET_IDLETIME", res.data.idleTime);
        this.getModel(url);
      } else {
        console.log(res);
      }
    },
    //获取数据库版本号
    async getModel(url) {
      try {
        const res = await getAllModel(url);
        if (res.code == 200) {
          const models = res.data;
          console.log("getModel models", models);
          if (models && models.length > 0) {
            this.$store.commit("SET_OWNMODEL", models[0].model);
          } else {
            this.$message.error("数据库版本未设置");
          }
        }
      } catch (err) {
        console.log("getModel", err);
      }
    },
    //登录
    handleSubmit(e) {
      const vm = this;
      if (e) {
        e.preventDefault();
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          const { user, passwd } = values;
          login(this.SERVERBASE_URL, user, encrypt(passwd)).then((res) => {
            if (res.code == 200) {
              vm.$message.success("登录成功！");
              if (res.data.token) {
                window.sessionStorage.setItem(
                  "token",
                  JSON.stringify({ authorization: res.data.token })
                );
              }
              if (!res.data.allow_sn) {
                this.updateUser(res.data);
              } else {
                const allow_sn = JSON.parse(res.data.allow_sn);
                const userInfo = {
                  ...res.data,
                  allow_sn,
                };
                this.$store.commit("SET_USERINFO", userInfo);
                vm.$router.push({ name: "home" });
                this.$store.commit("SET_BLINDREVIEW", this.blind);
              }
            } else {
              vm.$message.error(`登录失败!${res.err}`);
            }
          });
        }
      });
    },
    //更新用户信息
    async updateUser(user) {
      try {
        const allow_sn = {
          allow_sn: JSON.stringify({ patient_sn: "", doctor_sn: "" }),
        };
        const updateUser_res = await updateUser(
          this.SERVERBASE_URL,
          user.id,
          allow_sn
        );
        const userInfo_allow_sn = JSON.parse(updateUser_res.data.allow_sn);
        const userInfo = {
          ...updateUser_res.data,
          allow_sn: userInfo_allow_sn,
        };
        this.$store.commit("SET_USERINFO", userInfo);
        this.$router.push({ name: "home" });
      } catch (err) {
        console.log(err);
      }
    },
    async handBlur(){
      const user = this.form.getFieldValue("user");
      const res = await getUser(this.SERVERBASE_URL,user);
      if(res.code == 200){
        console.log("res",res.data)
        if(res.data && res.data.level == 6 ){
          this.options = [
            { label: "盲评", value: true },
          ];
          this.blind = true;
          this.$store.commit("SET_BLINDREVIEW", this.blind);
          this.blindShow = true;
        }else if(res.data && res.data.level == 7){
          this.blindShow = true;
          this.options = [
            { label: "盲评", value: true },
            { label: "非盲评", value: false },
          ];
        }else{
          this.blindShow = false;
          this.$store.commit("SET_BLINDREVIEW",true);
        }
      }
    },
    //确定关机
    async confirmShotDown() {
      console.log(
        "%c [ 确定关机 ]-125",
        "font-size:13px; background:pink; color:#bf2c9f;",
        systemShutDown
      );
      // try {
      //   await systemShutDown();
      // } catch (err) {
      //   throw new Error(err);
      // }
    },
  },
};
</script>

<style scoped lang="less">
@import "~@/assets/css/login.less";
</style>
